// curl解析和处理相关函数

// 基础curl解析函数
function parseCurlString(curlString) {
    // 检查是否有curl-parser-js库可用
    if (typeof window.parse_curl_js !== 'undefined' && typeof window.parse_curl_js.parse === 'function') {
        return window.parse_curl_js.parse(curlString);
    }
    
    // 如果没有外部库，使用简单的内置解析器
    return parseBasicCurl(curlString);
}

// 简单的内置curl解析器作为后备方案
function parseBasicCurl(curlString) {
    const result = {
        url: '',
        method: 'GET',
        headers: {},
        data: null,
        body: null
    };
    
    // 提取URL
    const urlMatch = curlString.match(/curl\s+['"]([^'"]+)['"]|curl\s+([^\s]+)/);
    if (urlMatch) {
        result.url = urlMatch[1] || urlMatch[2];
    }
    
    // 提取方法
    const methodMatch = curlString.match(/-X\s+([A-Z]+)/i);
    if (methodMatch) {
        result.method = methodMatch[1].toUpperCase();
    }
    
    // 提取headers
    const headerMatches = curlString.matchAll(/-H\s+['"]([^'"]+)['"]/g);
    for (const match of headerMatches) {
        const headerLine = match[1];
        const colonIndex = headerLine.indexOf(':');
        if (colonIndex > 0) {
            const key = headerLine.substring(0, colonIndex).trim();
            const value = headerLine.substring(colonIndex + 1).trim();
            result.headers[key] = value;
        }
    }
    
    // 提取data
    const dataMatch = curlString.match(/-d\s+['"]([^'"]+)['"]|--data\s+['"]([^'"]+)['"]|--data-binary\s+['"]([^'"]+)['"]/);
    if (dataMatch) {
        const data = dataMatch[1] || dataMatch[2] || dataMatch[3];
        result.data = data;
        result.body = data;
        
        // 尝试解析JSON
        try {
            result.body = JSON.parse(data);
        } catch (e) {
            // 如果不是JSON，保持原样
        }
    }
    
    return result;
}

// 切换curl导入区域的显示/隐藏
function toggleCurlImportSection() {
    const content = document.getElementById('curl-import-content');
    const icon = document.getElementById('curl-toggle-icon');
    
    if (content.classList.contains('hidden')) {
        content.classList.remove('hidden');
        icon.classList.remove('collapsed');
        icon.textContent = '▼';
    } else {
        content.classList.add('hidden');
        icon.classList.add('collapsed');
        icon.textContent = '▶';
    }
}

// 预处理curl命令，清理格式问题
function preprocessCurlCommand(curlCommand) {
    // 移除多余的空白字符和换行符
    let cleaned = curlCommand.trim();
    
    // 处理反斜杠换行符：将 \ + 换行符 替换为空格
    cleaned = cleaned.replace(/\\\s*\n\s*/g, ' ');
    cleaned = cleaned.replace(/\\\s*\r?\n\s*/g, ' ');
    
    // 清理多余的空格
    cleaned = cleaned.replace(/\s+/g, ' ');
    
    // 确保以curl开头
    if (!cleaned.toLowerCase().startsWith('curl')) {
        cleaned = 'curl ' + cleaned;
    }
    
    return cleaned;
}

// 解析curl命令并填充表单
function parseCurlCommand() {
    const curlCommand = document.getElementById('curl-command').value.trim();
    
    if (!curlCommand) {
        alert('请输入curl命令');
        return;
    }
    
    try {
        // 预处理curl命令
        const cleanedCurlCommand = preprocessCurlCommand(curlCommand);
        console.log('解析 - 原始命令:', curlCommand);
        console.log('解析 - 清理后命令:', cleanedCurlCommand);
        
        // 使用curl解析器
        const parsed = parseCurlString(cleanedCurlCommand);
        console.log('解析结果:', parsed);
        
        // 填充表单字段
        fillFormFromCurl(parsed);
        
        // 显示成功提示
        showToast('curl命令解析成功！', 'success');
        
    } catch (error) {
        console.error('curl解析失败:', error);
        alert('curl命令解析失败: ' + error.message);
    }
}

// 根据解析结果填充表单
function fillFormFromCurl(parsed) {
    try {
        // 提取URL信息
        const url = new URL(parsed.url);
        
        // 填充匹配模式 (使用hostname)
        document.getElementById('pattern').value = url.hostname;
        
        // 判断规则类型：如果有data或method不是GET，倾向于Mock规则
        const hasData = parsed.data || parsed.body;
        const isNotGet = parsed.method && parsed.method.toUpperCase() !== 'GET';
        
        if (hasData || isNotGet) {
            // 设置为Mock规则
            document.getElementById('rule_type').value = 'mock';
            toggleRuleTypeFields();
            
            // 填充Mock字段
            fillMockFields(parsed, url);
        } else {
            // 设置为代理规则
            document.getElementById('rule_type').value = 'proxy';
            toggleRuleTypeFields();
            
            // 填充代理字段
            fillProxyFields(url);
        }
        
    } catch (error) {
        console.error('填充表单失败:', error);
        alert('填充表单失败: ' + error.message);
    }
}

// 填充代理规则字段
function fillProxyFields(url) {
    document.getElementById('scheme').value = url.protocol.replace(':', '');
    document.getElementById('host').value = url.hostname;
    document.getElementById('port').value = url.port || (url.protocol === 'https:' ? 443 : 80);
    
    // 如果有路径，可以考虑设置strip_prefix
    if (url.pathname && url.pathname !== '/') {
        document.getElementById('strip_prefix').value = url.pathname;
    }
}

// 填充Mock规则字段
function fillMockFields(parsed, url) {
    // 设置默认状态码
    document.getElementById('mock_status').value = '200';
    
    // 设置内容类型
    const contentType = getContentTypeFromHeaders(parsed.headers) || 'application/json';
    document.getElementById('mock_content_type').value = contentType;
    
    // 设置数据源为内联
    document.getElementById('mock_data_source').value = 'inline';
    toggleMockDataFields();
    
    // 如果有请求数据，可以作为示例Mock内容
    if (parsed.data || parsed.body) {
        const mockContent = parsed.data || parsed.body;
        document.getElementById('mock_content').value = typeof mockContent === 'string' ? mockContent : JSON.stringify(mockContent, null, 2);
    } else {
        // 提供默认Mock内容
        document.getElementById('mock_content').value = JSON.stringify({
            "message": "Mock response from curl import",
            "url": url.href,
            "method": parsed.method || "GET"
        }, null, 2);
    }
    
    // 设置响应头
    if (parsed.headers && Object.keys(parsed.headers).length > 0) {
        // 过滤掉请求头，只保留适合作为响应头的
        const responseHeaders = filterResponseHeaders(parsed.headers);
        if (Object.keys(responseHeaders).length > 0) {
            document.getElementById('mock_headers').value = JSON.stringify(responseHeaders, null, 2);
        }
    }
}

// 从headers中提取Content-Type
function getContentTypeFromHeaders(headers) {
    if (!headers) return null;
    
    for (const [key, value] of Object.entries(headers)) {
        if (key.toLowerCase() === 'content-type') {
            return value.split(';')[0]; // 去掉charset等参数
        }
    }
    return null;
}

// 过滤出适合作为响应头的headers
function filterResponseHeaders(headers) {
    const responseHeaders = {};
    const responseHeaderNames = ['content-type', 'cache-control', 'access-control-allow-origin', 'x-custom'];
    
    for (const [key, value] of Object.entries(headers)) {
        const lowerKey = key.toLowerCase();
        // 只保留常见的响应头或自定义头
        if (responseHeaderNames.some(name => lowerKey.includes(name)) || lowerKey.startsWith('x-')) {
            responseHeaders[key] = value;
        }
    }
    
    return responseHeaders;
}

// 执行curl命令并获取Mock数据
async function executeCurlAndFillMock() {
    const curlCommand = document.getElementById('curl-command').value.trim();
    
    if (!curlCommand) {
        alert('请输入curl命令');
        return;
    }
    
    try {
        // 预处理curl命令，处理换行符和格式问题
        const cleanedCurlCommand = preprocessCurlCommand(curlCommand);
        console.log('原始命令:', curlCommand);
        console.log('清理后命令:', cleanedCurlCommand);
        
        // 首先解析curl命令
        const parsed = parseCurlString(cleanedCurlCommand);
        
        // 填充基本表单字段
        fillFormFromCurl(parsed);
        
        // 显示加载状态
        const executeBtn = event.target;
        const originalText = executeBtn.textContent;
        executeBtn.textContent = '执行中...';
        executeBtn.disabled = true;
        
        // 调用后端API执行curl
        const response = await fetch('/api/execute-curl', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                curl_command: cleanedCurlCommand
            })
        });
        
        if (!response.ok) {
            const errorText = await response.text();
            console.error('HTTP错误:', response.status, errorText);
            throw new Error(`HTTP ${response.status}: ${errorText}`);
        }
        
        const result = await response.json();
        console.log('API响应:', result);
        
        if (result.success) {
            // 执行成功，用真实响应数据填充Mock字段
            fillMockFieldsFromResponse(result.response_data);
            showToast('curl执行成功，Mock数据已填充！', 'success');
        } else {
            // 执行失败，显示详细错误信息
            console.error('执行失败:', result);
            const errorMsg = result.error || '执行curl命令失败';
            throw new Error(errorMsg);
        }
        
    } catch (error) {
        console.error('执行curl失败:', error);
        alert('执行curl失败: ' + error.message);
    } finally {
        // 恢复按钮状态
        const executeBtn = document.querySelector('button[onclick="executeCurlAndFillMock()"]');
        if (executeBtn) {
            executeBtn.textContent = originalText;
            executeBtn.disabled = false;
        }
    }
}

// 根据真实API响应填充Mock字段
function fillMockFieldsFromResponse(responseData) {
    // 确保设置为Mock规则
    document.getElementById('rule_type').value = 'mock';
    toggleRuleTypeFields();
    
    // 填充状态码
    if (responseData.status_code) {
        document.getElementById('mock_status').value = responseData.status_code;
    }
    
    // 填充内容类型
    if (responseData.content_type) {
        document.getElementById('mock_content_type').value = responseData.content_type;
    }
    
    // 填充响应内容
    if (responseData.content) {
        document.getElementById('mock_data_source').value = 'inline';
        toggleMockDataFields();
        document.getElementById('mock_content').value = responseData.content;
    }
    
    // 填充响应头
    if (responseData.headers && Object.keys(responseData.headers).length > 0) {
        document.getElementById('mock_headers').value = JSON.stringify(responseData.headers, null, 2);
    }
}

// 显示提示消息
function showToast(message, type = 'info') {
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    
    // 添加样式
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : '#007bff'};
        color: white;
        padding: 12px 20px;
        border-radius: 6px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        z-index: 10000;
        font-size: 14px;
        max-width: 300px;
        word-wrap: break-word;
    `;
    
    // 添加到页面
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 3000);
}

// 页面加载时初始化curl导入区域为折叠状态
document.addEventListener('DOMContentLoaded', function() {
    const curlContent = document.getElementById('curl-import-content');
    const curlIcon = document.getElementById('curl-toggle-icon');
    
    if (curlContent && curlIcon) {
        curlContent.classList.add('hidden');
        curlIcon.classList.add('collapsed');
        curlIcon.textContent = '▶';
    }
});